/*
*	东方财富获取所有A股票代码和名称
 */
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

type StockData struct {
	Data struct {
		Diff  []map[string]interface{} `json:"diff"`
		Total int                      `json:"total"`
	} `json:"data"`
}

func main() {
	baseURL := "https://20.push2.eastmoney.com/api/qt/clist/get?pn=%d&pz=100&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:13,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152"

	// 创建结果文件
	file, err := os.Create("stocks.csv")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	// 写入CSV标题（使用UTF-8 BOM确保中文兼容）
	file.WriteString("\xEF\xBB\xBF") // UTF-8 BOM
	file.WriteString("代码,名称,最新价,涨跌幅(%),涨跌额,成交量(手),成交额(元),振幅(%),最高价,最低价,今开,昨收\n")

	page := 1
	totalPages := 1

	for page <= totalPages {
		url := fmt.Sprintf(baseURL, page)
		fmt.Printf("正在抓取第 %d 页...\n", page)

		client := &http.Client{}
		req, err := http.NewRequest("GET", url, nil)
		if err != nil {
			fmt.Println("创建请求失败:", err)
			continue
		}
		req.Header.Set("Referer", "https://quote.eastmoney.com/")
		req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

		resp, err := client.Do(req)
		if err != nil {
			fmt.Println("请求失败:", err)
			time.Sleep(2 * time.Second)
			continue
		}

		body, err := io.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			fmt.Println("读取响应失败:", err)
			continue
		}

		var data StockData
		if err := json.Unmarshal(body, &data); err != nil {
			fmt.Println("解析JSON失败:", err)
			continue
		}

		// 第一页时计算总页数
		if page == 1 {
			totalPages = data.Data.Total/100 + 1
			fmt.Printf("共发现 %d 条数据，%d 页\n", data.Data.Total, totalPages)
		}

		// 处理本页数据
		for _, item := range data.Data.Diff {
			line := fmt.Sprintf("%v,%v,%v,%v,%v,%v,%v,%v,%v,%v,%v,%v\n",
				item["f12"], item["f14"], item["f2"], item["f3"], item["f4"],
				item["f5"], item["f6"], item["f7"], item["f15"], item["f16"],
				item["f17"], item["f18"])
			file.WriteString(line)
		}

		page++
		time.Sleep(1 * time.Second) // 避免请求过快
	}

	fmt.Println("数据抓取完成，已保存到 stocks.csv")
}
